<?php

namespace App\Http\Controllers\Admin;

use Illuminate\Http\Request;
use App\Repositories\CustomerNoteRepository;
use App\Repositories\CustomerRepository;

class CustomerNoteController extends AdminController
{
    public function __construct(CustomerNoteRepository $customerNote, CustomerRepository $customer)
    {
        $this->customerNote = $customerNote;
        $this->customer = $customer;
    }

    /**
     * Display a listing of the resource.
     *
     * @return Response
     */
    public function index(Request $request)
    {
        $customer = $this->customer->find($request->input('cid'));
        $notes = $this->customerNote->findAllBy('cid', $request->input('cid'));
        $user = $request->user();

        return view('admin.customer-notes.index', compact('customer', 'notes', 'user'));
    }

    /**
     * Show the form for creating a new resource.
     *
     * @return Response
     */
    public function create(Request $request)
    {
        $customer = $this->customer->find($request->input('cid'));

        return view('admin.customer-notes.create', compact('customer'));
    }

    /**
     * Store a newly created resource in storage.
     *
     * @param  Request  $request
     * @return Response
     */
    public function store(Request $request)
    {
        $request->request->add(['user_id' => $request->user()->id]);
        $result = $this->customerNote->create($request->all());

        if ($result) {
            return redirect()->route('admin.customer-note.index', ['cid'=>$request->input('cid')])->with('success', '保存笔记成功');
        }

        return back()->with('error', '保存笔记失败');
    }

    /**
     * Show the form for editing the specified resource.
     *
     * @param  int  $id
     * @return Response
     */
    public function edit($id)
    {
        $note = $this->customerNote->find($id);

        return view('admin.customer-notes.edit', compact('note'));
    }

    /**
     * Update the specified resource in storage.
     *
     * @param  Request  $request
     * @param  int  $id
     * @return Response
     */
    public function update(Request $request, $id)
    {
        $result = $this->customerNote->updateFind($request->all(), $id);

        if ($result) {
            return back()->with('success', '保存笔记成功');
        }

        return back()->with('error', '保存笔记失败'); 
    }

    /**
     * Remove the specified resource from storage.
     *
     * @param  int  $id
     * @return Response
     */
    public function destroy(Request $request, $id)
    {
        $result = $this->customerNote->delete($id);

        if ($result) {
            flash('success', '笔记删除成功');
            return response()->json(['code' => 200]);
        }

        flash('error', '笔记删除失败');
        return response()->json(['code' => 500]);
    }
}